"""
修正版监控客户端
确保每个CPU核心数据单独发送
"""
import psutil
import requests
from datetime import datetime

# 配置项
API_URL = "http://192.168.156.75:8000/v1/cpu"  # 替换为实际服务端地址
TIMEOUT = 5  # 请求超时时间(秒)

def get_hostname():
    """获取主机名"""
    try:
        return psutil.users()[0].name if psutil.users() else "unknown"
    except:
        return "unknown"

def collect_cpu_data():
    """采集CPU数据，返回每个核心的独立字典"""
    hostname = get_hostname()
    current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    # 为每个核心生成独立记录
    return [
        {
            "hostname": hostname,
            "date": current_time,
            "cpu_core": f"cpu{i}",  # 单个字符串
            "cpu_used": f"{percent:.2f}%",  # 单个字符串
            "cpu_free": f"{100 - percent:.2f}%"  # 单个字符串
        }
        for i, percent in enumerate(psutil.cpu_percent(percpu=True, interval=1))
    ]

def send_data():
    """发送数据到服务端"""
    for cpu_record in collect_cpu_data():  # 逐个发送每个核心的数据
        try:
            response = requests.post(
                API_URL,
                json=cpu_record,  # 发送单个核心的数据
                timeout=TIMEOUT
            )
            if response.status_code == 200:
                print(f"核心 {cpu_record['cpu_core']} 数据提交成功")
            else:
                print(f"核心 {cpu_record['cpu_core']} 提交失败，状态码：{response.status_code}")
        except requests.exceptions.RequestException as e:
            print(f"核心 {cpu_record['cpu_core']} 请求失败：{str(e)}")

if __name__ == '__main__':
    send_data()
